﻿using System;
namespace Validate.Net
{
    /// <summary>
    /// 校验数字的最大值
    /// </summary>
    public class ValidateMaxValueAttribute : AbstractValidateAttribute
    {
        /// <summary>
        /// 最大值
        /// </summary>
        private double maxValue;

        public ValidateMaxValueAttribute(double maxValue)
        {
            this.maxValue = maxValue;
        }

        public override bool Validate(object oValue, out string msg)
        {
            Type type = oValue?.GetType();
            if (!object.ReferenceEquals(typeof(int), type) &&
                !object.ReferenceEquals(typeof(long), type) &&
                !object.ReferenceEquals(typeof(double), type))
            {
                msg = $"特性[{this.GetType().Name}]只能校验数字类型";
                return false;
            }
            if (double.TryParse(oValue?.ToString(), out double value) && value <= this.maxValue)
            {
                msg = string.Empty;
                return true;
            }
            else
            {
                msg = $"最大值为：{this.maxValue}";
                return false;
            }
        }
    }
}
